/*
** action.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Tue Jul  5 10:02:43 2011 michael guidet
** Last update Tue Jul  5 10:08:44 2011 michael guidet
*/

#include "server.h"

t_action	ia_action[] =
  {
    {"avance", 7, action_avance, 0},
    {"droite", 7, action_droite, 1},
    {"gauche", 7, action_gauche, 2},
    {"voir", 7, action_voir, 3},
    {"inventaire", 1, action_inventaire, 4},
    {"prend", 7, action_prendre, 5},
    {"pose", 7, action_poser, 6},
    {"expulse", 7, action_expulse, 7},
    {"broadcast", 7, action_broadcast, 8},
    {"incantation", 0, action_incantation, 9},
    {"elevation", 300, action_elevation, 10},
    {"fork", 0, start_fork, 11},
    {"fin_fork", 42, end_fork, 12},
    {"connect_nbr", 0, action_connect, 13},
    {"msz", 0, map_size, 14},
    {"bct", 0, grh_bct, 15},
    {"mct", 0, grh_mct, 16},
    {"tna", 0, grh_tna, 17},
    {"ppo", 0, grh_ppo, 18},
    {"plv", 0, grh_plv, 19},
    {"pin", 0, grh_pin, 20},
    {"sgt", 0, grh_sgt, 21},
    {"sst", 0, grh_sst, 22},
    {NULL, 0, NULL, 0}
  };

void	refresh_action_list(char **action_list)
{
  int	i;

  free(action_list[0]);
  for (i = 0; i < 9; i++)
    action_list[i] = action_list[i + 1];
  action_list[9] = NULL;
}

void	add_to_action_list(t_fd *fd, t_env *e)
{
  int	i;

  while (fd->action_list[0] != NULL && fd->idaction == -1)
    {
      for (i = 0; ia_action[i].cmd != NULL; i++)
	if (!strncmp(fd->action_list[0], ia_action[i].cmd,
		     strlen(ia_action[i].cmd)))
	  {
	    if (ia_action[i].delay)
	      {
		fd->wait = (long)((float)ia_action[i].delay / (float)e->t
				  * 1000000.0f);
		fd->idaction = ia_action[i].id;
		fd->cmd = x_null(NULL, strdup(fd->action_list[0]), "strdup");
	      }
	    else
	      ia_action[i].execute(fd, e, fd->action_list[0]);
	  }
      refresh_action_list(fd->action_list);
    }
}

void	check_action_delay(t_fd *tmp, t_env *e)
{
  int   i;

  if (tmp->idaction != -1)
    {
      tmp->wait -= timeval_to_int(e->elapsed);
      if (tmp->wait <= 0)
	for (i = 0; ia_action[i].cmd != NULL; i++)
	  if (ia_action[i].id == tmp->idaction)
	    {
	      ia_action[i].execute(tmp, e, tmp->cmd);
	      if (tmp->cmd)
		free(tmp->cmd);
	      tmp->cmd = NULL;
	      break;
	    }
    }
}

void	execute_action(t_env *e)
{
  t_fd	*tmp;

  for (tmp = e->fd; tmp; tmp = tmp->next)
    {
      if (tmp->type == AI)
	{
	  tmp->pl->life -= timeval_to_int(e->elapsed);
	  if (tmp->pl->life <= 0)
	    {
	      tmp->type = DEAD;
	      continue;
	    }
	  check_action_delay(tmp, e);
	}
    }
  egg_check(e);
}
